package com.market2.session;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.ejb3.annotation.RemoteBinding;

import com.market2.dto.NegociationDto;
import com.market2.model.Negociation;
import com.market2.utils.EntityManagerThreadLocal;
import com.market2.utils.Globals;
import com.market2.utils.converter.ConverterUtil;

/**
 * Session Bean implementation class NegociationManager
 */
@Stateless @RemoteBinding(jndiBinding="Market2EAR/NegociationManager/remote")
public class NegociationManager implements NegociationManagerRemote
{
	@PersistenceContext(unitName=Globals.PERSISTENCE_UNIT_NAME)
	private EntityManager entityManager;
	
	@PostConstruct
	void init() {
		EntityManagerThreadLocal.set(entityManager);
	}
	
	@Override
	public NegociationDto getNegociationByNumero(Integer numero)
	{
		Negociation nego = entityManager.find(Negociation.class, numero);
		NegociationDto dto = ConverterUtil.convertTo(nego, NegociationDto.class);
		
		return dto;
	}

	@Override
	public List<NegociationDto> getLastNegociations(Integer nbLastNego)
	{
		if(nbLastNego == null || nbLastNego <= 0) {
			return null;
		}
		
		Query query = entityManager.createQuery("from Negociation");
		query.setMaxResults(nbLastNego);
		
		@SuppressWarnings("unchecked")
		List<Negociation> negociations = query.getResultList();
		return ConverterUtil.convertTo(negociations, NegociationDto.class);
	}
}
